﻿using AutoMapper;
using MediatR;
using RearLivestock.Common.Domains.hq;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Domains.zjy;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.Beginning.Api.Application.Command.BreedingSow
{
    public class SearchBreedingSowHandler : IRequestHandler<SearchBreedingSowCommand, Result<PageResultDto<BreedingSowDto>>>
    {
        /// <summary>
        /// 基本信息仓储
        /// </summary>
        private readonly IBaseRepository<BasicInformation> _basicInformationRepository;

        /// <summary>
        /// 种母期初仓储
        /// </summary>
        private readonly IBaseRepository<BreedingSows> _breedingSowsRepository;

        /// <summary>
        /// 栋舍仓储
        /// </summary>
        private readonly IBaseRepository<Bedrooms> _bedroomsRepository;

        /// <summary>
        ///  栏位仓储
        /// </summary>
        private readonly IBaseRepository<Fields> _fieldsRepository;

        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper _mapper;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchBreedingSowHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="basicInformationRepository"></param>
        /// <param name="breedingSowsRepository"></param>
        /// <param name="bedroomsRepository"></param>
        /// <param name="fieldsRepository"></param>
        /// <param name="mapper"></param>
        /// <param name="logger"></param>
        public SearchBreedingSowHandler(IBaseRepository<BasicInformation> basicInformationRepository,
            IBaseRepository<BreedingSows> breedingSowsRepository,
            IBaseRepository<Bedrooms> bedroomsRepository,
            IBaseRepository<Fields> fieldsRepository,
            IMapper mapper,
            ILogger<SearchBreedingSowHandler> logger)
        {
            _basicInformationRepository = basicInformationRepository;
            _breedingSowsRepository = breedingSowsRepository;
            _bedroomsRepository = bedroomsRepository;
            _fieldsRepository = fieldsRepository;
            _mapper = mapper;
            _logger = logger;
        }


        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<PageResultDto<BreedingSowDto>>> Handle(SearchBreedingSowCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<BreedingSowDto>>() { Code = (int)CommonErrorCode.Search };
            try
            {
                //实例化分页种母期初
                var page = new PageResultDto<BreedingSowDto>() { TotalCount = 0, PageCount = 0, List = new List<BreedingSowDto>() };
                //获取种母 栋舍 栏位
                var query = (from a in await _breedingSowsRepository.GetAll()
                             join b in await _bedroomsRepository.GetAll() on a.BedroomId equals b.BedroomId
                             join c in await _fieldsRepository.GetAll() on a.FieldId equals c.FieldId
                             join d in await _basicInformationRepository.GetAll() on a.BasicInforId equals d.BasicInforId
                             select new BreedingSowDto()
                             {
                                 BreedingSowId = a.BreedingSowId,
                                 DocumentNumber = a.DocumentNumber,
                                 OpeningDate = a.OpeningDate,
                                 BasicInforId = a.BasicInforId,
                                 BedroomId = a.BedroomId,
                                 FieldId = a.FieldId,
                                 DateofConversion = a.DateofConversion,
                                 Weight = a.Weight,
                                 IsBreedingSow = a.IsBreedingSow,
                                 BedroomName = b.BedroomName,
                                 FieldName = c.FieldName,
                                 EarNumber = d.EarNumber,
                                 CreatedOwner = a.CreatedOwner,
                                 CreatedTime = a.CreatedTime,
                                 UpdateOwner = a.UpdateOwner,
                                 UpdateTime = a.UpdateTime,
                                 ExamineOwner = a.ExamineOwner,
                                 ExamineTime = a.ExamineTime
                             });
                //种母耳号查询
                if (request.BasicInforId != 0)
                {
                    query = query.Where(x => x.BasicInforId == request.BasicInforId);
                }
                //转种日期开始时间
                if (request.StartTime != null)
                {
                    query = query.Where(x => x.DateofConversion >= request.StartTime);
                }
                //转钟日期结束时间
                if (request.EndTime != null)
                {
                    query = query.Where(x => x.DateofConversion <= request.EndTime);
                }
                //总页数
                page.TotalCount = query.Count();
                //总条数
                page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / request.PageSize);
                //跳过几条 显示几条
                page.List = query.OrderByDescending(d => d.OpeningDate).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                if (page.List.Count != 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = page;
                    result.Msg = "获取种母期初信息成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "获取种母期初信息异常" + ex.Message;
                _logger.LogError("获取种母期初信息异常" + ex.Message);
            }
            return result;
        }
    }
}
